const {
  promisify
} = require("util");
const figlet = promisify(require("figlet"));
const clear = require("clear");
const chalk = require("chalk");
const log = content => console.log(chalk.green(content))
const {
  clone
} = require("./download.js");
const open = require("open");

const spawn = async (...args) => {
  const options = args[args.length - 1]
  if (process.platform === 'win32') {
    console.log('win32');

    options.cmd = options.cwd;
    delete options.cwd
    // 设置shell选项为true 以隐式地调用cmd
    options.shell = true
  } else {
    console.log('Linux/Unix');
  }

  // 同步promise api
  const {
    spawn
  } = require("child_process");
  return new Promise(resolve => {
    const proc = spawn(...args)
    proc.stdout.pipe(process.stdout);
    proc.stdout.pipe(process.stderr);
    proc.on('close', () => {
      resolve()
    })
  })
}

module.exports = async name => {
  // 打印欢迎界面
  clear()
  const data = await figlet.textSync('Meng-cli!Welcome', {
    font: 'Ghost',
    horizontalLayout: 'default',
    verticalLayout: 'default',
    width: 200,
    whitespaceBreak: true
  });
  log(data)

  // 项目模板
  log("创建项目" + name)
  //github:su37josephxia/vue-template
  // await clone("github:su37josephxia/vue-template", name)

  // 下载依赖 npm i
  // 子进程
  log("安装依赖...")
  // await spawn('npm', ['install'], {
  //   cwd: `./${name}`
  // });

  log(`
👌安装完成：
To get Start:
===========================
    cd ${name}
    npm run serve
===========================
            `)

  open("http://localhost:8080");
  // await spawn('npm', ['run', 'serve'], {
  //   cwd: `./${name}`
  // })
}